using Godot;
using System.IO;
using ZFramework;

namespace PaintAWorld.Gd
{
    public partial class Client : Node
	{
		[Export]
		public Level level;

		[Export]
		public Label debug;

		[Export]
		public ColorRect colorDisplay;

		[Export]
		public DialogManager dialogManager;

		[Export]
		public VoxModel model;

		[ExportGroup("Dialogs")]
		[Export]
		public PackedScene pauseMenuDialogPrefab;
		[Export]
		public PackedScene commandDialogPrefab;

		[Export]
		public Node3D dir;

		private IWorld _world;

		public override void _Ready()
		{
			if (model != null)
			{
				_world = new LocalWorld(model.ToVoxelModel());
			}
			else
			{
				_world = new LocalWorld();
			}
			
			foreach (var vertex in new AABB(Vec3.Zero, new(1, 2, 3)).GetVertices())
			{
				GD.Print(vertex);
			}

			level.Setup(this, _world);
			level.EnableInput();
			HideCursor();

			dialogManager.Setup(this);
			dialogManager.StartDisplay += () =>
			{
				level.DisableInput();
				ShowCursor();
			};

			dialogManager.AllDialogClosed += () =>
			{
				level.EnableInput();
				HideCursor();
			};
		}

        public override void _UnhandledInput(InputEvent e)
		{
			if (e is InputEventKey ke && ke.Pressed)
			{
				switch (ke.Keycode)
				{
					case Key.Escape:
						dialogManager.ReplaceDialog(pauseMenuDialogPrefab);
						break;

					case Key.T:
						if (ke.AltPressed)
						{
							dialogManager.ReplaceDialog(commandDialogPrefab);
						}
						else
						{
							GD.Print("Add talk dialog!");
						}
						break;
				}
			}
		}

		public void UpdateHUD()
		{
			colorDisplay.Color = level.player.CurrentColor;
		}

		public void SubmitCommand(string command)
		{
			level.RunCommand(command);
		}

		public void ShowCursor()
		{
			Input.MouseMode = Input.MouseModeEnum.Visible;
		}

		public void HideCursor()
		{
			Input.MouseMode = Input.MouseModeEnum.Captured;
		}
	}
}